// DEPENDENCIES
// ============
var express = require("express"),
    http = require("http"),
    port = (process.env.PORT || 9000),
    server = module.exports = express(),
    $ = require('cheerio'),
    request = require('request'),
    logger = require('morgan');

var NodeCache = require( "node-cache" );
var myCache = new NodeCache();

var domain="http://www.51voa.com/"
// SERVER CONFIGURATION
// ====================
	server.use(logger());
server.configure(function () {

    server.use(express["static"](__dirname + "/../public"));


    server.use(express.errorHandler({

        dumpExceptions:true,

        showStack:true

    }));

    server.use(express.bodyParser());

    server.use(server.router);
});

// SERVER
// ======
itemModel= function(id, text, href,type){
     this.id = id; 
this.text = text; 
this.href = href||""; 
this.type=type||"";

};


//  request(domain, function (error, response, body) { 
// 	if (!error && response.statusCode == 200) {  
// 			$= $.load(body);   
// 			var ul = $("#left_nav ul");
// 			//console.log(ul[1].children);
// 			var itemArray =new Array();
// 			var li=ul[1].children;
// 			//console.log(li);
// 			for(var i=0; i<li.length; i++){
// 			if(li[i].children){
// 			 var item =new itemModel();
				 
// 				 item.id=i;
				
// 				var element = li[i].children;
// 			   for(var j=0; j<element.length; j++){
			 
// 			    item.href=element[j].attribs.href;
// 			     var text = element[j].children;
// 			     item.text=text[0].data;
				  
// 				  }
// 				  itemArray.push(item);
				  
// 			}
// 			console.log(itemArray);
// 			//	console.log(JSON.parse(itemArray));
			    
// 			}
			
// 	 }  
//  });
//  
// request("http://www.51voa.com/This_is_America_1.html", function (error, response, body) { 
//   if (!error && response.statusCode == 200) {  
//                 $= $.load(body);   
// 			var element = $("#list ul li a");
//                 //console.log(element);
//                 var itemArray =new Array();
//                  for(var j=0; j<element.length; j++){
             
// 			  var item =new itemModel();
//                        item.id=j;
// 			    item.href=element[j].attribs.href;
// 			     var text = element[j].children;
// 			     item.text=text[0].data+element[j].next.data;
// 				   itemArray.push(item);
// 				  }
				 
//                 console.log(itemArray);
//         }
//         });
var detailModel = function(title,content,mp3,author,time){
    this.title=title;
    this.content=content;
    this.mp3 = mp3;
    this.author= author;
    this.time =time;
    
}

var cacheObjec =function(time,data){
    
    
    this.time= time;
    this.data =data;
}
// request('http://www.51voa.com/VOA_Special_English/hundreds-of-migrants-feared-dead-62506.html', function (error, response, body) { 
//             if (!error && response.statusCode == 200) {  
//                  $= $.load(body);   
              
// 			  var titile = $("#title")[0].children[0].data;
//                var content =$("#content p")[0].children[0].data;
//                   var mp3 =$("#mp3")[0].attribs.href
//                   var author=$("#content .byline")[0].children[0].data;
//                 var time=$("#content .datetime")[0].children[0].data;
//                 var model = new detailModel();
//                 model.title=titile;
//                 model.content=content;
//                 model.mp3 = mp3;
//                 model.author=author;
//                 model.time=time;
            
//                 console.log(model);
//             }
//         });
    server.get('/api/*', function(req, res){ 
          
        var url = req.url.replace("/api/","");
        url = domain+url;
       
        if(myCache.get(url)!=undefined)
        {
            
            var cache = myCache.get(url);
             var   today = new Date();
            today.setHours(0,0,0,0);
             console.log("time="+cache.time);
             cacheTime=cache.time;
             cacheTime.setHours(0,0,0,0);
            if(cache.time>=today){
                console.log("get data");
                 res.send(cache.data);
                return ;
            }
            
            
        }
        request(url, function (error, response, body) { 
            if (!error && response.statusCode == 200) {  
                console.log("send API");
                 $= $.load(body);   
			var element = $("#list ul li a");
                var itemArray =new Array();
                 for(var j=0; j<element.length; j++){
             
			  var item =new itemModel();
                     item.type="detail";
                       item.id=j;
			    item.href=element[j].attribs.href;
			     var text = element[j].children;
			     item.text=text[0].data+element[j].next.data;
				   itemArray.push(item);
				  }
				// console.log(itemArray);
				var cachedvalue =new  cacheObjec();
                cachedvalue.time=new Date();
                cachedvalue.data= itemArray;
                myCache.set(url,cachedvalue);
                res.send(itemArray);
            }
        });
     }); 


    server.get('/detail/*', function(req, res){ 
          
        var url = req.url.replace("/detail/","");
        url = domain+url;
         console.log(url);
        
        if(myCache.get(url)!=undefined)
        {
            
            var cache = myCache.get(url);
             var   today = new Date();
            today.setHours(0,0,0,0);
             console.log("time="+cache.time);
             cacheTime=cache.time;
             cacheTime.setHours(0,0,0,0);
            if(cache.time>=today){
                console.log("get data");
                 res.send(cache.data);
                return ;
            }
            
            
        }
        
        request(url, function (error, response, body) { 
            if (!error && response.statusCode == 200) {  
                   $= $.load(body);   
            var titile = $("#title")[0].children[0].data;
               var content =$("#content ").html();
                content= content.replace(/img(.*)src=\"(.*)\.(jpg|gif)"(.*)>/gi,"img"+"$1"+"src=\"http:\/\/www.51voa.com/"+"$2"+"."+"$3"+"\""+"$4"+">");
              
                  var mp3 =$("#mp3")[0].attribs.href
                  var author=$("#content .byline")[0].children[0].data;
                var time=$("#content .datetime")[0].children[0].data;
                var model = new detailModel();
                model.title=titile;
                model.content=content;
                model.mp3 = mp3;
                model.author=author;
                model.time=time;
                 res.send(model);
            }
        });
     }); 




 
// Start Node.js Server
http.createServer(server).listen(port);

console.log('Welcome to Marionette-Require-Boilerplate!\n\nPlease go to http://localhost:' + port + ' to start using Require.js and Marionette');